package cn.com.xiaoshoujia.wxpay.utils;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONObject;

/**
 * @author yangrui
 */
public class HttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
     * 发送GET请求
     *
     * @param url
     * @return
     */
    public static String httpGet(String url) {

        CloseableHttpClient client = HttpClients.createDefault();
        String resultStr = null; // get请求返回结果

        HttpGet request = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build(); // 设置请求和传输超时时间（以毫秒为单位）
        request.setConfig(requestConfig);

        try {

            CloseableHttpResponse response = client.execute(request); // 发送请求

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 请求发送成功，并得到响应
                resultStr = EntityUtils.toString(response.getEntity(), "utf-8"); // 读取服务器返回过来的数据
            } else {
                logger.error("GET请求提交失败:" + url);
            }

        } catch (IOException e) {
            logger.error("GET请求提交失败:" + url, e);
        } finally {
            request.releaseConnection();
        }
        return resultStr;
    }

    /**
     * POST请求传输json参数
     *
     * @param url
     * @param jsonStr
     * @return
     */
    public static String httpPost(String url, String jsonStr) {

        CloseableHttpClient httpClient = HttpClients.createDefault(); // post请求返回结果
        HttpPost httpPost = new HttpPost(url);
        String resultStr = null;

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build(); // 设置请求和传输超时时间（以毫秒为单位）
        httpPost.setConfig(requestConfig);

        try {

            if (null != jsonStr) { // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonStr, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json"); // entity.setContentType("application/x-www-form-urlencoded");
                httpPost.setEntity(entity);
            }

            CloseableHttpResponse response = httpClient.execute(httpPost); // 发送POST请求

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 请求发送成功，并得到响应
                resultStr = EntityUtils.toString(response.getEntity(), "utf-8"); // 读取服务器返回过来的数据
            } else {
                logger.error("post请求提交失败:" + url);
            }

        } catch (Exception e) {
            logger.error("post请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return resultStr;
    }

    /**
     * post 请求
     *
     * @param url
     * @param params 建立HttpPost对象
     * @return
     */
    public static String hPost(String url, List<NameValuePair> params) {
        String result = "";
        //POST的URL
        HttpPost httppost = new HttpPost(url);
        //建立HttpPost对象
//    List<NameValuePair> params=new ArrayList<NameValuePair>();
        //建立一个NameValuePair数组，用于存储欲传送的参数
// params.add(new BasicNameValuePair("token","832ef44c7748d164ba258a1b95812c51"));
//    params.add(mulObject);
        //添加参数
        try {
            httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            //设置编码
            HttpResponse response = new DefaultHttpClient().execute(httppost);
            //发送Post,并返回一个HttpResponse对象
            if (response.getStatusLine().getStatusCode() == 200) {//如果状态码为200,就是正常返回
                result = EntityUtils.toString(response.getEntity());
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }


    public static void main(String[] args) {
        String url = "http://devapi.csbe.cn/user/userinfo";

        String json = "{\"token\":\"c6f54dcd090f17ba134be7583fc81150\"}";
        JSONObject json2 = JSONObject.fromObject(json);
        String jsonstr = json2.toString();
        String str = HttpClientUtil.httpPost(url, jsonstr);
        System.out.println(str);

    }
}